package com.xtgg.main;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.ImageLoaderHelper;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.ToastUtil;
import com.xtgg.util.Utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PhotosActivity extends BaseActivity implements OnClickListener 
{
	MyAdapter mAdapter;
	ArrayList<JSONObject> mArray = new ArrayList<JSONObject>();
	String mNumber = "0";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photos);

		((TextView) findViewById(R.id.center)).setText("宝宝相册");
    	((Button) findViewById(R.id.right)).setText("添加");
    	
    	findViewById(R.id.right).setOnClickListener(this);
    	findViewById(R.id.left).setOnClickListener(this);
    	
    	final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.PULL_FROM_END);
		ptrlvHeadlineNews
				.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						sendHttpRequest();
					}
				});

		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
			}
		});

		sendHttpRequest();
	}

	int mIndex = 0;
	@Override
	public void onClick(View arg0) 
	{
		int viewId = arg0.getId();
		switch(viewId)
		{
		case R.id.right:
		{

			Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
			getAlbum.setType("image/*");
			startActivityForResult(getAlbum, 3);
		}
			break;
			
		case R.id.left:
			finish();
			break;
			
		case R.id.camera:
			Intent intent = new Intent(this, SingleImageShowActivity.class);
			intent.putExtra("url", mArray.get(mIndex).getString("picurl"));
			startActivity(intent);
			mDialog.dismiss();
			break;

		case R.id.pic:
			mDialog.dismiss();
			sendDelHttpRequest();
			break;

		case R.id.cancel:
			mDialog.dismiss();
			break;
		}
	}

	private File mPhotoFile;
	@SuppressWarnings({ "deprecation" })
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null)
			return;

		Bitmap bitmap = null;
		if (resultCode == RESULT_OK) {
			if (requestCode == 3) {
				Uri uri = data.getData();
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = managedQuery(uri, proj, null, null, null);
				int column_index = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				cursor.moveToFirst();
				bitmap = Utils
						.getImageThumbnail(cursor.getString(column_index));
			}

			if (bitmap == null)
				return;
			
			bitmap = Utils.scalePic(bitmap, 480, 480);
			mPhotoFile = new File(Constants.PIC_PATH);// 将要保存图片的路径
			mPhotoFile.deleteOnExit();
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(mPhotoFile));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		sendImgHttpRequest();
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	private void sendDelHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					ToastUtil.showToastWithAlertPic("删除成功");
					reloadData();
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("act", "delPic");
		params.put("childid", getIntent().getStringExtra("childid"));
		params.put("picid", mArray.get(mIndex).getString("picid"));
		MgqRestClient.post(Constants.SETTING, params, loginHandler);
	}
	
	private void sendImgHttpRequest() {
		MgqDataHandler loginHandler = new MgqDataHandler(this, true, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					reloadData();
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("act", "addPic");
		params.put("childid", getIntent().getStringExtra("childid"));
		try 
		{
			params.put("filename0", mPhotoFile);
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		MgqRestClient.post(Constants.SETTING, params, loginHandler);
	}
	
	Dialog mDialog = null;
	void showImagePicker() {
		mDialog = new Dialog(this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_img_choose);
		((TextView)mDialog.findViewById(R.id.camera)).setText("查看");
		((TextView)mDialog.findViewById(R.id.pic)).setText("删除");
		mDialog.findViewById(R.id.camera).setOnClickListener(this);
		mDialog.findViewById(R.id.pic).setOnClickListener(this);
		mDialog.findViewById(R.id.cancel).setOnClickListener(this);
		mDialog.findViewById(R.id.dialog_layout).setOnClickListener(this);
		mDialog.show();
	}
	
	class MyAdapter extends BaseAdapter implements OnClickListener {
		public int getCount() {
			int size = mArray.size();
			return (size/4) + (size%4==0?0:1);
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		@SuppressLint("NewApi")
		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_photos, null);
				foodHold.img0 = (ImageView) convertView.findViewById(R.id.img0);
				foodHold.img1 = (ImageView) convertView.findViewById(R.id.img1);
				foodHold.img2 = (ImageView) convertView.findViewById(R.id.img2);
				foodHold.img3 = (ImageView) convertView.findViewById(R.id.img3);
				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}
			
			JSONObject item = mArray.get(4*position);
			ImageLoaderHelper.displayImage(R.drawable.img_default,foodHold.img0, item.getString("picurl"));
			foodHold.img0.setTag(String.valueOf(4*position));
			foodHold.img0.setOnClickListener(this);
			
			if(4*position + 1 < mArray.size())
			{
				item = mArray.get(4*position + 1);
				ImageLoaderHelper.displayImage(R.drawable.img_default,foodHold.img1, item.getString("picurl"));
				foodHold.img1.setTag(String.valueOf(4*position + 1));
				foodHold.img1.setOnClickListener(this);
				foodHold.img1.setVisibility(View.VISIBLE);
			}
			else foodHold.img1.setVisibility(View.INVISIBLE);

			if(4*position + 2 < mArray.size())
			{
				item = mArray.get(4*position + 2);
				ImageLoaderHelper.displayImage(R.drawable.img_default,foodHold.img2, item.getString("picurl"));
				foodHold.img2.setTag(String.valueOf(4*position + 2));
				foodHold.img2.setOnClickListener(this);
				foodHold.img2.setVisibility(View.VISIBLE);
			}
			else foodHold.img2.setVisibility(View.INVISIBLE);

			if(4*position + 3 < mArray.size())
			{
				item = mArray.get(4*position + 3);
				ImageLoaderHelper.displayImage(R.drawable.img_default,foodHold.img3, item.getString("picurl"));
				foodHold.img3.setTag(String.valueOf(4*position + 3));
				foodHold.img3.setOnClickListener(this);
				foodHold.img3.setVisibility(View.VISIBLE);
			}
			else foodHold.img3.setVisibility(View.INVISIBLE);

			return convertView;
		}

		@Override
		public void onClick(View arg0) {
			mIndex = Integer.valueOf((String)arg0.getTag());
			showImagePicker();
		}
	}
	
	void reloadData()
	{
		mNumber = "0";
		mArray.removeAll(mArray);
		mAdapter.notifyDataSetChanged();
		sendHttpRequest();
	}
	
	private void sendHttpRequest() {
		boolean show = false;
		if(mArray.size() == 0) show = true;
		
		MgqDataHandler loginHandler = new MgqDataHandler(this, show, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);

				if (ruser.getString("state").equals("1")) {
					JSONArray array = ruser.getJSONArray("data");
					int size = array.size();
					for(int i = 0; i < size; i++)
					{
						mArray.add(array.getJSONObject(i));
					}
					
					if(size > 0) mNumber = mArray.get(size - 1).getString("picid");
				}
				else if (ruser.getString("state").equals("2"))
				{
					showExitDialog();
				} else {
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}

				mAdapter.notifyDataSetChanged();
				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("act", "getPicList");
		params.put("childid", getIntent().getStringExtra("childid"));
		params.put("lastrecordid", mNumber);
		MgqRestClient.post(Constants.SETTING, params, loginHandler);
	}

	public final class FoodHolder {
		public ImageView img0;
		public ImageView img1;
		public ImageView img2;
		public ImageView img3;
	}
}
